package com.qianfeng.smartdevice.service.impl;


//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼            BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.smartdevice.constants.ResultCode;
import com.qianfeng.smartdevice.dto.UserDto;
import com.qianfeng.smartdevice.event.UserLoginEvent;
import com.qianfeng.smartdevice.exceptions.*;
import com.qianfeng.smartdevice.mapper.MenuMapper;
import com.qianfeng.smartdevice.mapper.RoleMapper;
import com.qianfeng.smartdevice.mapper.UserMapper;
import com.qianfeng.smartdevice.pojo.Menu;
import com.qianfeng.smartdevice.pojo.Role;
import com.qianfeng.smartdevice.pojo.User;
import com.qianfeng.smartdevice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by jackiechan on 2020/12/7 20:25
 *
 * @Author jackiechan
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public int addUser(UserDto userDto) {
        if (userDto == null) {
            throw new AddErrorException("数据为空", ResultCode.NULL_DATA);
        }
        Long userId = getUserIdByUserName(userDto.getUsername());
        if (userId != null) {
            throw new AddErrorException("用户" + userDto.getUsername() + "已经存在", ResultCode.USER_EXIST_ERROR);
        }
        //设置密码的 md5
        String passwordMD5 = DigestUtils.md5DigestAsHex((userDto.getUsername() + userDto.getPassword()).getBytes());
        userDto.setPassword(passwordMD5);
        return userMapper.addUser(userDto);
    }

    @Override
    public Long getUserIdByUserName(String username) {
        if (username == null) {
            return null;
        }
        return userMapper.getUserIdByUserName(username);
    }

    @Override
    public User getUserByUsername(String username) {
        if (!StringUtils.isEmpty(username)) {
            return userMapper.getUserByUsername(username);
        }
        return null;
    }

    @Override
    public User getUserByUId(Long id) {
        if (id == null) {
            throw new MyBaseErrorxception("id 不能为空", ResultCode.DATA_NOT_ALLOWED);
        }
        try {
            User user = userMapper.getUserByUId(id);
            if (user == null) {
                throw new MyBaseErrorxception("无数据", ResultCode.NULL_DATA);
            }
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyBaseErrorxception(e.getMessage(), ResultCode.NULL_DATA);
        }
    }

    @Override
    public PageInfo<User> findAllUsers(int pageNum, int pageSize, int status, String username) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> allUsers = userMapper.findAllUsers(username, status);
        allUsers.forEach(user -> user.setPassword(null));
        System.err.println(allUsers);
        PageInfo<User> pageInfo = new PageInfo<>(allUsers);
        return pageInfo;
    }

    @Override
    public int updateUserLoginTime(Long id, Date date) {
        if (id == null || date == null) {
            return 0;
        }
        return userMapper.updateUserLoginTime(id, date);
    }

    @Override
    public int updateUserLoginTimeByUserName(String username, Date date) {
        return userMapper.updateUserLoginTimeByUserName(username,date);
    }


    public User login(UserDto userDto) {
        if (userDto == null) {
            throw new LoginErrorException("账号密码错误", ResultCode.USERNAME_PASSWORDERROR);
        }
        User user = getUserByUsername(userDto.getUsername());
        if (user != null && "1".equalsIgnoreCase(user.getStatus()) && DigestUtils.md5DigestAsHex((userDto.getUsername() + userDto.getPassword()).getBytes()).equalsIgnoreCase(user.getPassword())) {
            user.setPassword(null);
            //设置本次登陆时间
            user.setCurrentlogin(new Date());
            //更新上次登录时间为本次登录时间
            updateUserLoginTime(user.getId(), new Date());
            return user;
        } else {
            throw new LoginErrorException("账号密码错误", ResultCode.USERNAME_PASSWORDERROR);
        }
    }

    @Override
    public int updateUser(UserDto userDto) {
        if (userDto == null) {
            throw new UpdateErrorException("用户信息不对", ResultCode.DATA_NOT_ALLOWED);
        }
        if (!StringUtils.isEmpty(userDto.getPassword())) {
            String passwordMD5 = DigestUtils.md5DigestAsHex((userDto.getUsername() + userDto.getPassword()).getBytes());
            userDto.setPassword(passwordMD5);
        }
        try {
            userMapper.updateUser(userDto);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpdateErrorException(e.getMessage(), ResultCode.DATA_NOT_ALLOWED);
        }

    }

    @Override
    public void deleteUsers(String[] ids) {
        if (ids == null) {
            throw new DeleteErrorException("没有传递 ids", ResultCode.DATA_NOT_ALLOWED);
        }
        try {
            userMapper.deleteUsers(ids);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DeleteErrorException(e.getMessage(), ResultCode.DATA_NOT_ALLOWED);
        }


    }

    @Override
    public User getUserWithPermisByUserName(String username) {
        User user = userMapper.getUserByUsername(username);
        List<Role> roleList = roleMapper.getRolesByUserId(user.getId());
        if (roleList != null) {
//            if (roleList.size() == 1) {
//                Role role = roleList.get(0);
//                List<Menu> menuList = menuMapper.getMenusByRoleId(role.getId());
//                role.setMenuList(menuList);
//            }
            roleList.forEach(role -> {
                List<Menu> menuList = menuMapper.getMenusByRoleId(role.getId());
                role.setMenuList(menuList);
            });
        }
        user.setRoleList(roleList);

        return user;
    }

    @EventListener
    public void onEvent(UserLoginEvent event) {
        updateUserLoginTimeByUserName(event.getUsername(), new Date());
    }
}
